﻿namespace API
{
	/// <summary>
	/// Mqtt客户端
	/// </summary>
	public class FmMqttClient
	{
		private static IMqttClient mqttclient = null;
		private static MqttClientOptions options = null;
		/// <summary>
		/// 连接mqtt
		/// </summary>
		/// <param name="ip">ip地址</param>
		/// <param name="port">端口</param>
		/// <param name="username">账号</param>
		/// <param name="password">密码</param>
		public void ConnectMqttServerAsync(string ip, int port, string username, string password)
		{
			mqttclient = new MqttFactory().CreateMqttClient();
			options = new MqttClientOptionsBuilder()
				   .WithTcpServer(ip, port)
				   .WithCredentials(username, password)
				   .WithClientId($"AVCSOFTWAREFRAMEWORKTEMPLATE@SUB|EP#{Util.CreateGUID().ToString().Substring(0, 8).ToUpper()}")
				   .Build();

			mqttclient.ConnectedAsync += Mqttclient_ConnectedAsync;
			mqttclient.DisconnectedAsync += Mqttclient_DisconnectedAsync;
			mqttclient.ApplicationMessageReceivedAsync += Mqttclient_ApplicationMessageReceivedAsync;
			mqttclient.ConnectAsync(options);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="arg"></param>
		/// <returns></returns>
		private Task Mqttclient_DisconnectedAsync(MqttClientDisconnectedEventArgs arg)
		{
			Log.Write("连接失败");
			mqttclient.ConnectAsync(options);
			return Task.CompletedTask;
		}

		/// <summary>
		/// 发布消息
		/// </summary>
		/// <param name="data"></param>
		public void Publish(string data)
		{
			var message = new MqttApplicationMessage
			{
				Topic = "/log/avcsoftwareframeworktemplate",
				Payload = Encoding.UTF8.GetBytes(data),
				QualityOfServiceLevel = MqttQualityOfServiceLevel.AtLeastOnce,
				Retain = false//必须为false，不能改为true
			};
			mqttclient.PublishAsync(message);
		}
		/// <summary>
		/// 消息接收
		/// </summary>
		/// <param name="arg"></param>
		/// <returns></returns>
		private Task Mqttclient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
		{
			try
			{
				//逻辑处理
			}
			catch (Exception ex)
			{
				Log.WriteException(ex);
			}

			return Task.CompletedTask;
		}

		/// <summary>
		/// 链接操作
		/// </summary>
		/// <param name="arg"></param>
		/// <returns></returns>
		private Task Mqttclient_ConnectedAsync(MqttClientConnectedEventArgs arg)
		{
			Log.Write("连接成功");
			//xx服务
			//mqttclient.SubscribeAsync("/event/xx", MqttQualityOfServiceLevel.AtLeastOnce);
			return Task.CompletedTask;
		}

	}
}
